<template>
  <div>
    <!-- 防抖输入框示例 -->
    <input 
      type="text" 
      v-model="inputValue"
      @input="handleDebouncedInput"
      placeholder="输入会防抖(500ms)"
    >
    <p>实时值: {{ inputValue }}</p>
    <p>防抖值: {{ debouncedValue }}</p>

    <!-- 防抖按钮示例 -->
    <button @click="debouncedClick">
      点击防抖(1秒)
    </button>
    <p>点击次数: {{ clickCount }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// 防抖函数封装
const useDebounce = (fn, delay = 500) => {
  let timeoutId;
  
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 输入框防抖示例
const inputValue = ref('');//输入数值
const debouncedValue = ref('');//防抖数值

const updateDebouncedValue = () => {
  debouncedValue.value = inputValue.value;
  console.log('防抖更新:', debouncedValue.value);
};

const handleDebouncedInput = useDebounce(updateDebouncedValue, 500);

// 按钮点击防抖示例
const clickCount = ref(0);

const handleClick = () => {
  clickCount.value++;
  console.log(`防抖点击 (${clickCount.value})`);
};

const debouncedClick = useDebounce(handleClick, 1000);
</script>